//
//  ByUIPayInfoVC.m
//  chequanbao_ios
//
//  Created by pro on 17/5/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIPayInfoVC.h"

// vc
#import "ByUIShopsPaySuccessVC.h"   // 支付成功

// cell
#import "ByCellPayType.h"

// model
#import "ByNetWechatPayModel.h"

// api
#import "ByNetWechatPayApi.h"
#import "ByNetAliPayApi.h"

@interface ByUIPayInfoVC () <UITableViewDelegate, UITableViewDataSource>

// view
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *bottomButton;
// data
@property (nonatomic, copy) NSArray *infoDicArray;
@property (nonatomic, copy) NSMutableArray *selectArray;

@end

@implementation ByUIPayInfoVC

#pragma mark - 懒加载
- (NSArray *)infoDicArray {
    
    if (!_infoDicArray) {
        NSDictionary *dic1 = @{@"icon"      : @"Pay_ailPay",
                               @"title"     : @"支付宝支付",};
        NSDictionary *dic2 = @{@"icon"      : @"Pay_wechat",
                               @"title"     : @"微信支付",};
       
        _infoDicArray = @[dic1, dic2];
    }
    return _infoDicArray;
}
- (NSMutableArray *)selectArray {
    
    if (!_selectArray) {
        _selectArray = [[NSMutableArray alloc] init];
    }
    return _selectArray;
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - view method
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"付款详情";
    
    [self.selectArray addObject:@YES];
    [self.selectArray addObject:@NO];
    
    [self addLeftBackBarButtonItem];
    
    [self createHeaderView];
    [self createTableView];
    [self createButton];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aliPaySuccess:) name:@"aliPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aliPayFailure:) name:@"aliPayFailure" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatPaySuccess:) name:@"wechatPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatPayFailure:) name:@"wechatPayFailure" object:nil];
}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    self.headerView.top = self.view.safeAreaInsets.top;
    self.titleLabel.top = self.headerView.bottom + 15;
    self.table.top = self.titleLabel.bottom + 10;
    self.bottomButton.bottom = self.view.height - self.view.safeAreaInsets.bottom;
}

// 创建头视图
- (void)createHeaderView {
    
    CGFloat x, y, width, height;
    
    x = 10;
    y = 64;
    width = SCREEN_WIDTH - x * 2;
    height = 80;
   
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    self.headerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.headerView];
    self.headerView.layer.cornerRadius = 5;
    
    /*
     钱,￥19.00
     */
    x = 0;
    y = 0;
    width = 100;
    height = self.headerView.height;
    UILabel *paylabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    paylabel.adjustsFontSizeToFitWidth = YES;
    paylabel.font = FONT(15);
    paylabel.text = [NSString stringWithFormat:@"￥%.2lf", self.orderModel.fee.floatValue / 100];
    paylabel.textColor = [UIColor orangeColor];
    paylabel.textAlignment = NSTextAlignmentRight;
    [self.headerView addSubview:paylabel];
    paylabel.right = self.headerView.width - 10;
    
    
    x = 10;
    y = 0;
    width = paylabel.left - x;
    height = paylabel.height;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    titleLabel.adjustsFontSizeToFitWidth = YES;
    titleLabel.font = FONT(15);
    titleLabel.text = self.name;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.headerView addSubview:titleLabel];
}
// 创建表视图
- (void)createTableView {

    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.headerView.bottom + 15, 200, 20)];
    _titleLabel.adjustsFontSizeToFitWidth = YES;
    _titleLabel.font = B_FONT(16);
    _titleLabel.text = @"选择支付方式";
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:_titleLabel];
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(10, _titleLabel.bottom + 10, SCREEN_WIDTH - 20, self.infoDicArray.count * 60) style:UITableViewStylePlain];
    self.table.backgroundColor = [UIColor whiteColor];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.tableFooterView = [UIView new];
    self.table.layer.cornerRadius = 5;
}
- (void)createButton {
    
    CGFloat x, y, width, height;
    x = 0;
    y = SCREEN_HEIGHT - 50;
    width = SCREEN_WIDTH;
    height = 50;
    _bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.backgroundColor = rgba(15, 20, 39, 1);
    _bottomButton.backgroundColor = BY_THEME_COLOR;
    [_bottomButton setFrame:CGRectMake(x, y, width, height)];
    
    NSString *title = [NSString stringWithFormat:@"确认支付￥%.2lf", self.orderModel.fee.floatValue / 100];
    [_bottomButton setTitle:title forState:UIControlStateNormal];
    [_bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_bottomButton addTarget:self action:@selector(confirmPay) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomButton];
}


#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoDicArray.count;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
   
    ByCellPayType *cell = [tableView dequeueReusableCellWithIdentifier:@"payCell"];
    if (cell == nil) {
        cell = [[ByCellPayType alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"payCell"];
        
    }
    cell.infoDic = self.infoDicArray[indexPath.row];
    cell.select = [self.selectArray[indexPath.row] boolValue];
    
    return cell;
    
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 60;
}


// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row < self.infoDicArray.count) {
        for (int i = 0; i < self.selectArray.count; i ++) {
            if (i == indexPath.row) {
                [self.selectArray replaceObjectAtIndex:i withObject:@YES];
            } else {
                [self.selectArray replaceObjectAtIndex:i withObject:@NO];
            }
        }
        [self.table reloadData];
    }
    
    
}


#pragma mark - 点击
- (void)confirmPay {
    
    NSLog(@"确认支付");
    
    // 支付方式
    NSInteger payment = 0;
    for (int i = 0; i < 2; i++) {
        if ([self.selectArray[i] boolValue]) {
            payment = i;
        }
    }
    if (payment == 0){
        [self alipay];
    }else{
        [self wechatPay];
    }
}

// 支付宝
- (void)alipay{
//    if (!self.payModel.isLegal){
//      [ByCoreToolAlert showFailureWithText:@"该订单存在安全问题"];
//      return;
//    }
    ByNetParamsModel *params = [[ByNetParamsModel alloc] init];
    params.productDes = @"有车有保支付宝支付";
    params.productName = @"有车有保支付宝支付";
    params.tradeNO = self.orderModel.order_code;
    NSLog(@"tradeNO = %@", params.tradeNO);
    params.totalFee = [NSString stringWithFormat:@"%.2lf", self.orderModel.fee.floatValue / 100];
//    params.totalFee = @"0.01";
    params.showUrl = @"http://domain.merchant.com/payment_notify";
    [ByNetAliPayApi AliPayGoPay:params success:^(ByNetBaseResult *result) {
        
    }failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
        
    }];
    
}


- (void)aliPaySuccess:(NSNotification *)notification {
    
    [self backAction:YES];
}

- (void)aliPayFailure:(NSNotification *)notification {
    
    
    [self backAction:NO];
}



// 微信支付
- (void)wechatPay{
    [ByCoreToolAlert showOnlyText:@"微信支付"];
    
    ByNetWechatPayModel *payModel = [[ByNetWechatPayModel alloc] init];
    payModel.code = self.orderModel.order_code;
    
    [ByCoreToolAlert showLoadind:@"正在发起支付..."];
    [ByNetWechatPayApi wechatForePayRequest:payModel failure:^(ByNetBaseResult *result) {
        [self backAction:NO];
    }];
    
}

- (void)wechatPaySuccess:(NSNotification *)notification {
    [self backAction:YES];
}

- (void)wechatPayFailure:(NSNotification *)notification {
    [self backAction:NO];
    
}
#pragma mark - 返回处理（成功或失败）
- (void)backAction:(BOOL)isSuccess {
    
    if (isSuccess) {    // 成功
        NSLog(@"支付成功");
        
        [ByCoreToolAlert showSuccessWithText:@"支付成功"];
        dispatch_after(dispatch_time(0, NSEC_PER_SEC * 2), dispatch_get_main_queue(), ^{
            ByUIShopsPaySuccessVC *vc = [[ByUIShopsPaySuccessVC alloc] init];
            NSLog(@"%@",self.orderModel);
            vc.store_id = self.store_id;
            [self by_normalPush:vc hasNavi:YES];
        });
    } else {            // 失败
        NSLog(@"支付失败");
        dispatch_after(dispatch_time(0, NSEC_PER_SEC * 2), dispatch_get_main_queue(), ^{
            [self by_normalPopVC:@"ByUIPayVC"];
        });
    }
}


@end
